package com.yaozheng.vocationaltraining.activity;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.yaozheng.vocationaltraining.R;
import com.yaozheng.vocationaltraining.adapter.QuestionsAnswerAdapter;
import com.yaozheng.vocationaltraining.bean.CreatorBean;
import com.yaozheng.vocationaltraining.bean.HundredQuestionsEncyclopediaItemBean;
import com.yaozheng.vocationaltraining.bean.ImageBean;
import com.yaozheng.vocationaltraining.bean.QuestionAnswerItemBean;
import com.yaozheng.vocationaltraining.bean.QuestionDetailBean;
import com.yaozheng.vocationaltraining.iview.ILoadMoreView;
import com.yaozheng.vocationaltraining.iview.IQuestionsDetailView;
import com.yaozheng.vocationaltraining.manage.ListViewLoadMoreManage;
import com.yaozheng.vocationaltraining.service.QuestionsDetailService;
import com.yaozheng.vocationaltraining.service.impl.QuestionsDetailServiceImpl;
import com.yaozheng.vocationaltraining.utils.BitmapLoader;
import com.yaozheng.vocationaltraining.utils.Constants;
import com.yaozheng.vocationaltraining.utils.ErrorUtils;
import com.yaozheng.vocationaltraining.utils.LogUtils;
import com.yaozheng.vocationaltraining.utils.TypeUtils;
import com.yaozheng.vocationaltraining.widget.CircleImageView;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;

/**
 * Created by moon on 2017/11/9.
 */

@EActivity(R.layout.activity_questions_detail)
public class QuestionsDetailActivity extends BaseActivity
        implements SwipeRefreshLayout.OnRefreshListener, ILoadMoreView,
        IQuestionsDetailView {
    BitmapLoader userBitmapLoader;

    @ViewById
    TextView headRightText;

    @ViewById
    ImageView add_answer_imageview;

    @ViewById
    ListView listView;
    @ViewById
    TextView title_textview;
    @ViewById
    CircleImageView userAvatarImage;
    @ViewById
    TextView username_textview;
    @ViewById
    TextView storename_textview;
    @ViewById
    TextView position_textview;
    @ViewById
    TextView time_textview;
    @ViewById
    TextView desc_textview;



    @ViewById
    LinearLayout reply_tip_layout;
    @ViewById
    TextView reply_num_textview;
    @ViewById
    LinearLayout praise_tip_layout;
    @ViewById
    TextView praise_num_textview;
    @ViewById
    LinearLayout reward_tip_layout;
    @ViewById
    TextView reward_num_textview;
    @ViewById
    LinearLayout click_tip_layout;
    @ViewById
    TextView click_num_textview;

    @ViewById
    ImageView status_imageview;
    @ViewById
    ImageView have_adopt_imageview;
    @ViewById
    ImageView attachment_imageview;


    /**
     * 下拉刷新
     */
    @ViewById
    SwipeRefreshLayout swipeRefreshLayout;

    ListViewLoadMoreManage listViewLoadMoreManage;

    @Bean(QuestionsDetailServiceImpl.class)
    QuestionsDetailService questionsDetailService;

    QuestionsAnswerAdapter questionsAnswerAdapter;
    ArrayList<QuestionAnswerItemBean> questionAnswerItemData = new ArrayList<>();

    int questionId;
    QuestionDetailBean questionDetail;
    int detailType = 0;//0：回答界面 ，1审核界面 ， 2采纳界面
    int resolved;

    int usertype;
    int uid;

    int lastId;
    LayoutInflater inflater;

    @AfterViews
    public void initView() {
        setHeadTitle("百问百答");
        headRightText.setText(this.getResources().getText(R.string.myStr));
        inflater = this.getLayoutInflater();
        userBitmapLoader = new BitmapLoader(Glide.with(this), R.drawable.user_img);
        questionsDetailService.init(this);

        usertype = this.getIntentInt("usertype");
        uid = this.getIntentInt("uid");
        if (usertype ==1){
            detailType = 1;
        }

        questionId = this.getIntentInt("questionId");

        listViewLoadMoreManage = new ListViewLoadMoreManage(this, this,
                listView);
        swipeRefreshLayout.setOnRefreshListener(this);
//		swipeRefreshLayout.postDelayed(new Runnable() {
//			@Override
//			public void run() {
//				swipeRefreshLayout.setRefreshing(true);
//
//			}
//		}, 500);


        questionsAnswerAdapter = new QuestionsAnswerAdapter(this,
                questionAnswerItemData);
        listView.setAdapter(questionsAnswerAdapter);

        loadQuestionDetail();

        headRightText.setVisibility(View.VISIBLE);

        status_imageview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (questionDetail != null &&
                        questionDetail.getStatus() == 1){ //表示已审核
                    questionsDetailService.reViewQuestion(questionId,true);
                }else{
                    questionsDetailService.reViewQuestion(questionId,false);
                }
            }
        });


    }

    @Override
    protected void onResume() {
        super.onResume();
        onRefresh();
    }

    /**
     * 保存我的
     */
    @Click(R.id.headRightText)
    public void headRightClick() {

        Intent intent = new Intent();
        intent.putExtra("uid",uid);
        intent.setClassName(this,
                Constants.ME_QUESTION_ENCYCLOPEDIA_ACTIVITY_CLASS_NAME);
        this.startActivity(intent);

    }


    @Click(R.id.add_answer_imageview)
    public void addAnswerImageViewClick() {

        if(questionDetail != null){
            Intent intent = new Intent();
            intent.setClassName(this,
                    Constants.ADD_ANSWER_ACTIVITY_CLASS_NAME);
            intent.putExtra("questionId",questionId);
            intent.putExtra("title",questionDetail.getTitle());
            this.startActivity(intent);
        }else {
            LogUtils.println("该问题已不存在!");
        }


    }

    private void loadQuestionDetail() {
        questionsDetailService.loadQuestionDetail(questionId);
    }

    @Override
    public void onRefresh() {
        lastId = 0;
        loadData();
    }

    @Override
    public void loadMoreData() {
        if(questionAnswerItemData != null && questionAnswerItemData.size() > 0){
            int lastId = questionAnswerItemData.get(questionAnswerItemData.size() -1).getId();
            if (lastId > 0) {
                this.lastId = lastId;
                loadData();
            }
        }
    }

    public void loadData() {
        questionsDetailService.list(lastId,questionId);
    }

    @UiThread
    @Override
    public void responseSuccess(JSONObject jsonObject) {
        try {
            cancelLoadDataProgressDialog();
            JSONArray dataList = TypeUtils.getJsonArray(jsonObject, "data","answers");
            if (dataList != null) {
                if (lastId == 0) {
                    questionAnswerItemData.clear();
                }

                for (int i = 0; i < dataList.size(); i++) {
                    JSONObject jsonObject2 = dataList.getJSONObject(i);

                    QuestionAnswerItemBean bean = new QuestionAnswerItemBean();
                    bean.setId(jsonObject2.getInt("id"));
                    bean.setQid(jsonObject2.getInt("qid"));
                    bean.setCateId(jsonObject2.getInt("cateId"));
                    bean.setBody(jsonObject2.getString("body"));
                    bean.setLike(jsonObject2.getBoolean("like"));
                    bean.setSelected(jsonObject2.getInt("selected"));
                    bean.setStatus(jsonObject2.getInt("status"));
                    bean.setCreatedTime(jsonObject2.getString("createdTime"));
                    bean.setLikeCnt(jsonObject2.getInt("likeCnt"));
                    bean.setScore(jsonObject2.getInt("score"));

                    JSONArray imageArray = TypeUtils.getJsonArray(jsonObject2,"images");
                    if (imageArray != null){
                        for (int j = 0; j < imageArray.size(); j++) {
                            JSONObject imageObject = imageArray.getJSONObject(j);
                            ImageBean imageBean = new ImageBean();
                            imageBean.setId(imageObject.getInt("id"));
                            imageBean.setPath(imageObject.getString("path"));
                            bean.getImages().add(imageBean);
                        }
                    }

                    JSONObject creatorObject = TypeUtils.getJsonObject(jsonObject2, "creator");
                    CreatorBean creatorBean = new CreatorBean();
                    creatorBean.setUid(creatorObject.getInt("uid"));
                    creatorBean.setUsername(creatorObject.getString("username"));
                    creatorBean.setName(creatorObject.getString("name"));
                    creatorBean.setAvatar(creatorObject.getString("avatar"));
                    creatorBean.setPosition(creatorObject.getString("position"));
                    creatorBean.setStoreId(creatorObject.getInt("storeId"));
                    creatorBean.setStoreName(creatorObject.getString("storeName"));
                    bean.setCreator(creatorBean);

                    questionAnswerItemData.add(bean);
                }

                questionsAnswerAdapter.setData(questionAnswerItemData,detailType,resolved,uid,usertype);
                questionsAnswerAdapter.notifyDataSetChanged();
            }
        } catch (Exception e) {
            ErrorUtils.outErrorLog(e);
        }
    }

    @UiThread
    @Override
    public void responseError(String error) {

    }

    @Override
    public void cancelLoadDataProgressDialog() {
        swipeRefreshLayout.setRefreshing(false);
        listViewLoadMoreManage.loadMoreComplete();
    }


    @UiThread
    @Override
    public void questionDetailSuccess(JSONObject jsonObject) {
        JSONObject jsonOjbect2 = TypeUtils.getJsonObject(jsonObject, "data","question");

        questionDetail = new QuestionDetailBean();
        questionDetail.setId(jsonOjbect2.getInt("id"));
        questionDetail.setTitle(jsonOjbect2.getString("title"));
        questionDetail.setBody(jsonOjbect2.getString("body"));
        questionDetail.setScore(jsonOjbect2.getInt("score"));
        questionDetail.setClick(jsonOjbect2.getInt("click"));
        questionDetail.setAnswer(jsonOjbect2.getInt("answer"));
        questionDetail.setLike(jsonOjbect2.getInt("like"));
        questionDetail.setResolved(jsonOjbect2.getInt("resolved"));
        questionDetail.setStatus(jsonOjbect2.getInt("status"));
        questionDetail.setCreatedTime(jsonOjbect2.getString("createdTime"));
        CreatorBean creatorBean = new CreatorBean();

        JSONObject creatorObject = TypeUtils.getJsonObject(jsonOjbect2, "creator");
        creatorBean.setUid(creatorObject.getInt("uid"));
        creatorBean.setUsername(creatorObject.getString("username"));
        creatorBean.setName(creatorObject.getString("name"));
        creatorBean.setAvatar(creatorObject.getString("avatar"));
        creatorBean.setPosition(creatorObject.getString("position"));
        creatorBean.setStoreId(creatorObject.getInt("storeId"));
        creatorBean.setStoreName(creatorObject.getString("storeName"));
        questionDetail.setCreator(creatorBean);

        JSONArray imageArray = TypeUtils.getJsonArray(jsonOjbect2,"images");
        if (imageArray != null){
            for (int i = 0; i < imageArray.size(); i++) {
                JSONObject imageObject = imageArray.getJSONObject(i);
                ImageBean imageBean = new ImageBean();
                imageBean.setId(imageObject.getInt("id"));
                imageBean.setPath(imageObject.getString("path"));
                questionDetail.getImages().add(imageBean);
            }
        }

        title_textview.setText(questionDetail.getTitle());
        username_textview.setText(questionDetail.getCreator().getName());
        storename_textview.setText(questionDetail.getCreator().getStoreName());
        if(!TextUtils.isEmpty(questionDetail.getCreator().getPosition()) && !"null".equals(questionDetail.getCreator().getPosition())){
            position_textview.setText(questionDetail.getCreator().getPosition());
        }else {
            position_textview.setText("");
        }
        //position_textview.setText(questionDetail.getCreator().getPosition());
        time_textview.setText(questionDetail.getCreatedTime());
        desc_textview.setText(questionDetail.getBody());

        if (questionDetail.getAnswer() < 1){
            reply_tip_layout.setVisibility(View.GONE);
        }else {
            reply_tip_layout.setVisibility(View.VISIBLE);
            reply_num_textview.setText(questionDetail.getAnswer()+"");
        }
        if(questionDetail.getLike() < 1){
            praise_tip_layout.setVisibility(View.GONE);
        }else {
            praise_tip_layout.setVisibility(View.VISIBLE);
            praise_num_textview.setText(questionDetail.getLike()+"");
        }
        if (questionDetail.getScore() < 1){
            reward_tip_layout.setVisibility(View.GONE);
        }else {
            reward_tip_layout.setVisibility(View.VISIBLE);
            reward_num_textview.setText(questionDetail.getScore()+"");
        }
        if(questionDetail.getClick() < 1){
            click_tip_layout.setVisibility(View.GONE);
        }else {
            click_tip_layout.setVisibility(View.VISIBLE);
            click_num_textview.setText(questionDetail.getClick()+"");
        }
        if (questionDetail.getStatus() == 1){ //表示已审核
            status_imageview.setImageResource(R.drawable.reviewed);
        }else {
            status_imageview.setImageResource(R.drawable.not_reviewed);
        }
        have_adopt_imageview.setVisibility(View.GONE);
        //加载图片
        userBitmapLoader.displayImage(questionDetail.getCreator().getAvatar(), userAvatarImage);

        if(questionDetail.getImages() != null && questionDetail.getImages().size() > 0){
            attachment_imageview.setVisibility(View.VISIBLE);
            userBitmapLoader.displayImage(questionDetail.getImages().get(0).getPath(),attachment_imageview);
        }else {
            attachment_imageview.setVisibility(View.GONE);
        }

        if(detailType != 1){
            status_imageview.setVisibility(View.GONE);
            if (questionDetail.getCreator().getUid() == uid){
                detailType = 2;
                add_answer_imageview.setVisibility(View.GONE);
            }else {
                detailType = 0;
                add_answer_imageview.setVisibility(View.VISIBLE);
            }
        }else {
            add_answer_imageview.setVisibility(View.VISIBLE);
        }


        resolved = questionDetail.getResolved();
        if(resolved == 1){//已解决
            add_answer_imageview.setVisibility(View.GONE);
        }


    }

    @Override
    public void questionDetailError(String error) {

    }

    @UiThread
    @Override
    public void reViewQuestionSuccess(JSONObject jsonObject) {
        if (questionDetail.getStatus() == 1) { //表示已审核
            questionDetail.setStatus(0);
            status_imageview.setImageResource(R.drawable.not_reviewed);
        }else {
            questionDetail.setStatus(1);
            status_imageview.setImageResource(R.drawable.reviewed);
        }
    }

    @Override
    public void reViewQuestionError(String error) {

    }

    @UiThread
    @Override
    public void reViewAnswerSuccess(JSONObject jsonObject) {

    }

    @Override
    public void reViewAnswerError(String error) {

    }

    @UiThread
    @Override
    public void answerSelectSuccess(JSONObject jsonObject) {
        Toast.makeText(this,"回复采纳成功",Toast.LENGTH_SHORT).show();
    }

    @UiThread
    @Override
    public void answerSelectError(String error) {
        Toast.makeText(this,error,Toast.LENGTH_SHORT).show();
    }

    @UiThread
    @Override
    public void setLikeSuccess(JSONObject jsonObject,int answerId) {
        alertMessage("点赞成功");
        for(QuestionAnswerItemBean bean : questionAnswerItemData){
            if(bean.getId() == answerId){
                bean.setLikeCnt(bean.getLikeCnt() + 1);
                bean.setLike(true);
                questionsAnswerAdapter.setData(questionAnswerItemData,detailType,resolved,uid,usertype);
                questionsAnswerAdapter.notifyDataSetChanged();
            }
        }

    }

    @Override
    public void setLikeError(String error) {
        alertMessage(error);
    }

    @UiThread
    @Override
    public void addAnswerRewardSuccess(JSONObject jsonObject) {
        Toast.makeText(this,"追加奖励成功",Toast.LENGTH_SHORT).show();
    }

    @UiThread
    @Override
    public void addAnswerRewardError(String error) {
        Toast.makeText(this,error,Toast.LENGTH_SHORT).show();
    }

    public void reViewAnswer(int answerId, boolean approved) {
        questionsDetailService.reViewAnswer(answerId,approved);
    }

    public void answerSelect(int answerId) {
        questionsDetailService.answerSelect(answerId);
    }

    public void setLike(int answerId) {
        questionsDetailService.setLike(answerId);
    }

    public void addAnswerReward(int answerId, String score) {
        questionsDetailService.addAnswerReward(answerId,score);
    }
}
